package com.raychi.demo.action;

import java.sql.SQLException;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.raychi.demo.entity.Student;
import com.raychi.demo.service.StudentService;

public class StudentLoginAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	private Student student;
	private StudentService studentService;

	/**
	 * 学生登录界面
	 * @return 登陆见面的jsp
	 */
	public String login(){
		
		return "login";
	}
	
	
	/**
	 * 学生登出将session失效
	 * @return 登出后回到登录界面
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public String outLogin() throws ClassNotFoundException, SQLException{
		HttpSession session = ServletActionContext.getRequest().getSession(false);
		if(session != null){
			session.invalidate();
		}
		return login();
	}
	
	
	/**
	 * 个人信息查询或者成绩查询界面
	 * @return
	 */
	public String cho(){
		return "cho";
	}
	
	
	/**
	 * 列出指定id的学生的个人信息
	 * @return 显示该学生信息的界面
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public String list1() throws ClassNotFoundException, SQLException{
		student = studentService.getStudentById(student.getId());
		return "list1";
	}
	
	
	/**
	 * 更改学生的个人信息
	 * @return 更改完成后回到现实学生个人信息的界面
	 * @throws Exception 
	 */
	public String update() throws Exception{
		studentService.update(student);
		return list1();
	}
	
	/**
	 * 学生注册界面
	 * @return
	 */
	public String regist(){
		return "regist";
	}
	
	/**
	 * 通过各种验证将满足条件的新用户信息存入数据库
	 * @return 新用户注册成功后返回到登录界面
	 * @throws Exception
	 */
	public String save() throws Exception{
		if (student.getUsername() == null || student.getUsername().length() == 0) {
			super.addActionError("请输入用户名");
		}
		if (StringUtils.isEmpty(student.getPassword()) || StringUtils.isEmpty(student.getPassword2())) {
			super.addActionError("请输入密码");
		}
		if(!student.getPassword().equals(student.getPassword2())){
			super.addActionError("2次密码输入不一致");
		}
		
		if (super.hasActionErrors()) {
			return "regist";
		}
		
		String rsl = studentService.save(student);
		if ("fail".equals(rsl)) {
			super.addActionError("用户名已被注册");
			return "regist";
		}
		super.addActionMessage("注册成功");
		return "login";
	}
	
	
	/**
	 * 验证用户输入的账号密码，如果验证成功 通过重定向到学生的选择界面
	 * 失败 就在页面上显示用户名或密码错误，并且返回到登录界面
	 */
	public String input(){
		boolean rsl = studentService.loing(student.getUsername(), student.getPassword());
		if (rsl) {
			return SUCCESS;
		}
		super.addActionError("用户名或密码错误！");
		return "login";
	}
	
	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}


	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}

}
